package com.cong.security.browser;

import com.cong.security.core.properties.SecurityProperties;
import com.cong.security.core.support.SimpleResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO
 * @Author single-聪
 * @Date 2020/2/7 12:43
 * @Version 1.0.1
 **/
@Slf4j
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    private String logoutUrl;

    private ObjectMapper objectMapper = new ObjectMapper();

    public MyLogoutSuccessHandler(String logoutUrl) {
        this.logoutUrl = logoutUrl;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("退出成功,自定义选择退出逻辑");
        if (StringUtils.isBlank(logoutUrl)) {
            log.info("未配置退出页面,返回json");
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse("退出成功")));
        } else {
            log.info("配置退出页面,跳转至退出页");
            httpServletResponse.sendRedirect(logoutUrl);
        }
    }
}
